from loguru import logger

from com.arcfox.manager.redis_task_manager import RedisTaskManager
from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.school.processor.base_processor import BaseProcessor
from com.arcfox.util.muilty_coroutine_util import concurrency
import com.arcfox.school.util.yzy_decrypt_util as yzy_util


class YZYUniversityScoreProcessor(BaseProcessor):

    async def parse_and_save_data(self, result_json, p_map, university_name):
        parse_result = []
        for item in result_json["result"]:
            courses_arr = item["courses"]
            for course in courses_arr:
                fractions = course["fractions"]
                for fraction in fractions:
                    # university_name = yzy_util.decrypt_font(fraction["collegeName"])
                    university_uid = self.generate_school_uid(university_name)
                    province = p_map[int(fraction["provinceCode"])]
                    # exist = await self.__exist_university_province_score(university_uid, province,
                    #                                                      fraction["year"], fraction["course"],
                    #                                                      fraction["batch"])
                    # if exist:
                    #     logger.info("已经存在,直接返回,{},{},{},{},{}", university_name,fraction["year"],province,fraction["batch"],fraction["course"])
                    #     continue
                    obj = {
                        "province": province,
                        "subject_item": fraction["course"],
                        "score_year": fraction["year"],
                        "batch_name": fraction["batch"],
                        "max_score": self.__get_integer_value(yzy_util.decrypt_font(fraction["maxScore"])),
                        "min_score": self.__get_integer_value(yzy_util.decrypt_font(fraction["minScore"])),
                        "avg_score": self.__get_integer_value(yzy_util.decrypt_font(fraction["avgScore"])),
                        "min_rank": self.__get_integer_value(yzy_util.decrypt_font(fraction["minRank"])),
                        "max_rank": self.__get_integer_value(yzy_util.decrypt_font(fraction["maxRank"])),
                        "avg_rank": self.__get_integer_value(yzy_util.decrypt_font(fraction["avgRank"])),
                        "enroll_count": self.__get_integer_value(yzy_util.decrypt_font(fraction["enterNum"])),
                        "enroll_code": yzy_util.decrypt_font(fraction["collegeEnrollCode"]),
                        "university_name": university_name,
                        "university_uid": university_uid,
                        "choose_subject_text": yzy_util.decrypt_font(fraction["chooseSubjectText"]),
                        "plan_enroll_count": self.__get_integer_value(yzy_util.decrypt_font(fraction["planNum"])),
                        "extra_info": yzy_util.decrypt_font(fraction["collegeNameText"])
                    }

                    logger.info("获取实体信息:{}", obj)
                    parse_result.append(obj)
        await self.__insert_university_province_score(tasks=parse_result)

        # await self.__insert_province_score(tasks=parse_result)

    def __get_integer_value(self, value):
        # logger.info("获取整数值:{}", value)
        if value == '':
            return None
        return int(value)

    @concurrency(30)
    async def __insert_university_province_score(self, **params):
        task = params['task']
        mapping = db.MysqlMapping("tb_university_score_2")
        exist = await mapping.query(
            {
                "university_uid": task["university_uid"],
                "province": task["province"],
                "score_year": task["score_year"],
                "subject_item": task["subject_item"],
                "batch_name": task["batch_name"],
                "extra_info": task["extra_info"]
            }, ["id"])
        if exist:
            logger.info("已经存在{}", task)
            return
        await mapping.insert(task)

